/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cc.siyecao.mapper.provider.entity;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.util.Objects;

/**
 * 实体中字段和列的对应关系接口，记录字段上提供的列信息
 *
 * @author liuzh
 */
@Accessors(fluent = true)
public class EntityColumn extends Column {
    /**
     * 实体类字段
     */
    @Getter
    protected final EntityField field;
    /**
     * 所在实体类
     */
    @Getter
    @Setter
    protected EntityTable entityTable;

    protected EntityColumn(EntityField field) {
        this.field = field;
    }

    public static EntityColumn of(EntityField field) {
        return new EntityColumn( field );
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof EntityColumn)) return false;
        EntityColumn that = (EntityColumn) o;
        return column().equals( that.column() );
    }

    @Override
    public int hashCode() {
        return Objects.hash( column() );
    }

    @Override
    public String toString() {
        return columnEqualsProperty();
    }

    @Override
    public Class<?> javaType() {
        return field().getType();
    }

    /**
     * 带指定前缀的属性名
     *
     * @param prefix 指定前缀，需要自己提供"."
     */
    @Override
    public String property(String prefix) {
        return prefix + field().getName();
    }

    @Override
    public String property(String prefix, String suffix) {
        return prefix + field().getName() + suffix;
    }

    /**
     * 当字段类型为 String 时，返回 prefixproperty != null and prefixproperty != '' 形式的字符串.
     * 其他类型时和 {@link #notNullTest()} 方法一样.
     *
     * @param prefix 指定前缀，需要自己提供"."
     */
    @Override
    public String notEmptyTest(String prefix) {
        if (field().getType() == String.class) {
            return notNullTest( prefix ) + " and " + property( prefix ) + " != '' ";
        }
        return notNullTest();
    }
}
